import { useCallback, useEffect, useState } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { View, Image, Text, ScrollView } from '@tarojs/components'
import { Button, Popup } from '@nutui/nutui-react-taro'
import { Footer } from '@/components/index'
import {
  getQuestionIndexList,
  getQuestionById,
  saveAnswer,
  submitExam
} from '@/axios/exam'
import bk1 from '@/img/comm/bk_1.svg'
import bk2 from '@/img/comm/bk_2.svg'
import successIcon from '@/img/comm/success.svg'
// import TopicProgressBar from './components/TopicProgressBar'
import Topic from './components/Topic'

import './index.scss'

interface ExamIndexProps {}

const ExamIndex: React.FC<ExamIndexProps> = () => {
  const {
    params: { questionId = '' }
  } = useRouter()

  const [current, setCurrent] = useState<number>(0)
  const [currentQuestionId, setCurrentQuestionId] = useState<number>(0)
  const [indexList, setIndexList] = useState<API.QuestionIndexItem[]>([])
  const [questionRes, setQuestionRes] = useState<API.QuestionProps>({})
  const [visible, setVisible] = useState<boolean>(false)

  const getQuestionIndexData = async (id: string | number) => {
    Taro.showLoading({
      title: 'loading...',
      mask: true
    })
    try {
      const list = await getQuestionIndexList()
      let currentId: number = 0
      // 当在考试中的时候
      if (id && id !== 'null') {
        const currentIndex = list.findIndex(
          item => item.questionId == Number(id)
        )

        setCurrent(currentIndex)
        currentId = Number(id)
      } else {
        currentId = list[0].questionId
      }
      setCurrentQuestionId(currentId)
      setIndexList(list)
    } catch (e) {}
  }

  // 获取当前题目
  const getCurrentQuestion = useCallback(async () => {
    try {
      if (!currentQuestionId) return
      const results = await getQuestionById({
        questionId: currentQuestionId
      })
      setQuestionRes(results)
      Taro.hideLoading()
    } catch {}
  }, [currentQuestionId])

  useEffect(() => {
    getCurrentQuestion()
  }, [getCurrentQuestion])

  useEffect(() => {
    getQuestionIndexData(questionId)
  }, [questionId])

  const handleClickNext = async () => {
    const { answerVOList } = questionRes
    const selectAn = answerVOList?.find(answer => answer.select)
    if (selectAn && Object.keys(selectAn).length > 0) {
      Taro.showLoading({
        title: 'loading...'
      })
      const params = {
        answerId: selectAn.answerId,
        questionId: questionRes.questionId
      }
      try {
        await saveAnswer(params)
        Taro.hideLoading()
        // 最后一个题目时 判断题目是否全部完成
        if (current == indexList.length - 1) {
          const list = await getQuestionIndexList()
          const results = list.find(item => item.done == false)
          if (results && Object.keys(results).length > 0) {
            Taro.showToast({
              title: '题目未全部完成!',
              icon: 'error'
            })
            return
          }
          // 已全部答完 提交试卷
          await submitExam()
          setVisible(true)
          return
        }
      } catch {
        return
      }
    } else {
      if (current == indexList.length - 1) {
        Taro.showToast({
          title: '题目未全部完成!',
          icon: 'error'
        })
        return
      }
    }
    const nextQuestion = indexList[current + 1]
    getQuestionIndexData(nextQuestion.questionId)
  }

  const handleClickPre = async () => {
    const preQuestion = indexList[current - 1]
    getQuestionIndexData(preQuestion.questionId)
  }

  const handleClickAnswer = (id: number) => {
    const resutls = questionRes.answerVOList?.map(item => {
      item.select = item.answerId == id
      return item
    })
    setQuestionRes({
      ...questionRes,
      answerVOList: resutls
    })
  }

  const handleClickIndex = (current: number) => {
    const currentQuestion = indexList[current]
    getQuestionIndexData(currentQuestion.questionId)
  }

  const handeClickToIndex = () => {
    Taro.redirectTo({
      url: '/subPackages/pages/user/index'
    })
  }

  return (
    <View className='exam_page flex_column'>
      {/* <TopicProgressBar current={current} sourceData={indexList} /> */}
      <View className='topicProgress_box'>
        <ScrollView
          className='topic_index_box'
          scrollIntoViewAlignment='center'
          scrollIntoView={`topic_index_${current}`}
          scrollWithAnimation
          scrollX
          showScrollbar={false}
        >
          <View className='flex_row id_list'>
            {indexList.map((value, index) => (
              <View
                key={index}
                className='number_box flex_column'
                id={`topic_index_${index}`}
                onClick={() => handleClickIndex?.(index as number)}
              >
                <View
                  className={
                    current == index ? 'number_text active_text' : 'number_text'
                  }
                >
                  {index + 1}
                </View>
                <View
                  className={value.done ? 'status_box done' : 'status_box'}
                ></View>
              </View>
            ))}
          </View>
        </ScrollView>
        <View className='progress_box'>
          <View className='default_box'></View>
          <View
            className='active_box'
            style={{ width: ((current + 1) / indexList.length) * 100 + '%' }}
          ></View>
        </View>
      </View>
      <View className='topic_box'>
        <Topic sourceData={questionRes} change={handleClickAnswer} />
        <View className='img_box'>
          <Image className='img_1' src={bk1} />
          <Image className='img_2' src={bk2} />
        </View>
        <View className='btn_box flex_row'>
          <Button
            style={{ visibility: current == 0 ? 'hidden' : 'visible' }}
            onClick={handleClickPre}
          >
            上一题
          </Button>
          <Button type='info' onClick={handleClickNext}>
            {current == indexList.length - 1 ? '提交问卷' : '下一题'}
          </Button>
        </View>
      </View>
      <Popup
        visible={visible}
        closeOnOverlayClick={false}
        className='i_popup flex_column'
        onClose={() => setVisible(false)}
      >
        <Image src={successIcon} className='success_icon' />
        <Text className='pop_text'>答题成功</Text>
        <Button type='info' className='btn' onClick={handeClickToIndex}>
          确定
        </Button>
      </Popup>
      <Footer />
    </View>
  )
}

export default ExamIndex
